import { WaterSourceAPI, Topic, Post } from './api-client.js';

export interface SearchResult {
  query: string;
  topics: TopicContent[];
}

export interface TopicContent {
  id: string;
  title: string;
  url: string;
  full_content: string;  // 完整内容
  preview_content: string; // 预览内容（关键部分）
  created_at: string;
  username: string;
  like_count: number;
  posts_count: number;
  relevance: number;
}

export class SearchProcessor {
  private api: WaterSourceAPI;
  private baseUrl: string;
  private maxContentLength: number = 4000; // 限制内容长度，避免超出大模型输入上限

  constructor(api: WaterSourceAPI) {
    this.api = api;
    this.baseUrl = 'https://shuiyuan.sjtu.edu.cn';
  }

  /**
   * 获取与查询相关的内容
   */
  public async getRelevantContent(
    query: string,
    maxResults: number = 5
  ): Promise<SearchResult> {
    try {
      console.log(`开始搜索关键词: ${query}`);
      
      // 获取搜索结果
      const searchResult = await this.api.search(query);
      const topics = searchResult.topics || [];
      
      console.log(`找到 ${topics.length} 个相关主题`);
      
      // 如果没有结果，返回空数组
      if (topics.length === 0) {
        return { query, topics: [] };
      }
      
      // 优先选取回复数较多的主题（通常表示讨论更活跃）
      const sortedByReplies = [...topics].sort((a, b) => b.posts_count - a.posts_count);
      const limitedTopics = sortedByReplies.slice(0, maxResults);
      const topicContents: TopicContent[] = [];
      
      // 获取每个主题的详细内容
      for (const topic of limitedTopics) {
        try {
          console.log(`获取主题内容: ${topic.id}`);
          
          // 获取完整主题内容
          const fullTopic = await this.api.getTopic(topic.id.toString());
          
          // 处理所有楼层的内容
          let allPostContents: {username: string; content: string}[] = [];
          let mainPostUsername = '';
          
          if (fullTopic.post_stream && fullTopic.post_stream.posts && fullTopic.post_stream.posts.length > 0) {
            // 处理所有可用的帖子
            for (const post of fullTopic.post_stream.posts) {
              const postContent = this.api.extractPostContent(post);
              const username = post.username || '未知用户';
              
              // 记录第一个帖子的用户名（主楼发布者）
              if (mainPostUsername === '') {
                mainPostUsername = username;
              }
              
              // 添加格式化的帖子内容
              if (postContent.trim()) {
                allPostContents.push({
                  username,
                  content: postContent
                });
              }
            }
            
            // 如果帖子数量超过已加载的帖子数，尝试获取更多帖子
            if (fullTopic.post_stream.stream.length > fullTopic.post_stream.posts.length) {
              console.log(`获取主题 ${topic.id} 的额外帖子`);
              try {
                // 获取前5个额外楼层，避免请求过多数据
                const additionalPostIds = fullTopic.post_stream.stream
                  .slice(fullTopic.post_stream.posts.length, fullTopic.post_stream.posts.length + 5)
                  .map(id => id.toString());
                
                if (additionalPostIds.length > 0) {
                  const additionalPosts = await this.api.getTopicPosts(topic.id.toString(), additionalPostIds);
                  
                  // 处理额外获取的帖子
                  for (const post of additionalPosts) {
                    const postContent = this.api.extractPostContent(post);
                    const username = post.username || '未知用户';
                    
                    if (postContent.trim()) {
                      allPostContents.push({
                        username,
                        content: postContent
                      });
                    }
                  }
                }
              } catch (error) {
                console.warn(`获取额外帖子失败: ${error instanceof Error ? error.message : String(error)}`);
              }
            }
          }
          
          // 合并所有楼层内容并限制总长度
          let fullContent = allPostContents.map(post => `【${post.username}】: ${post.content}`).join('\n\n');
          if (fullContent.length > this.maxContentLength) {
            // 尝试在句号处智能截断
            const lastSentenceEnd = fullContent.lastIndexOf('。', this.maxContentLength);
            if (lastSentenceEnd > this.maxContentLength * 0.7) {
              fullContent = fullContent.substring(0, lastSentenceEnd + 1) + "...(内容被截断)";
            } else {
              fullContent = fullContent.substring(0, this.maxContentLength) + "...(内容被截断)";
            }
          }
          
          // 提取关键内容作为预览（基于查询词相关性）
          const previewContent = this.extractKeyContent(allPostContents, query, topic.title);
          
          // 组装主题内容对象
          topicContents.push({
            id: topic.id.toString(),
            title: topic.title,
            url: `${this.baseUrl}/t/${topic.id}`,
            full_content: fullContent,
            preview_content: previewContent,
            created_at: topic.created_at,
            username: mainPostUsername,
            like_count: topic.like_count || 0,
            posts_count: fullTopic.posts_count || 0,
            relevance: this.calculateRelevance(query, topic.title, allPostContents)
          });
          
        } catch (error) {
          console.error(`获取主题 ${topic.id} 内容失败:`, error instanceof Error ? error.message : String(error));
          // 继续处理下一个主题
        }
      }
      
      // 按相关性排序结果
      topicContents.sort((a, b) => b.relevance - a.relevance);
      
      return {
        query,
        topics: topicContents
      };
    } catch (error) {
      console.error('搜索处理失败:', error instanceof Error ? error.message : String(error));
      throw new Error(`搜索处理失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  /**
   * 提取主题中与查询相关的关键内容
   */
  private extractKeyContent(
    posts: {username: string; content: string}[],
    query: string,
    title: string
  ): string {
    // 查询关键词，分词后去重
    const keywords = [...new Set(
      query.toLowerCase()
        .replace(/[,.?!，。？！]/g, ' ')
        .split(' ')
        .filter(word => word.length > 1)
    )];
    
    // 如果没有有效关键词，返回前几个帖子作为预览
    if (keywords.length === 0) {
      return posts.slice(0, 3).map(post => `【${post.username}】: ${this.truncateText(post.content, 150)}`).join('\n\n');
    }
    
    // 计算每个帖子的相关性得分
    const scoredPosts = posts.map(post => {
      let score = 0;
      const lowerContent = post.content.toLowerCase();
      
      // 关键词匹配得分
      keywords.forEach(keyword => {
        const matches = lowerContent.match(new RegExp(keyword, 'g'));
        if (matches) {
          score += matches.length * 2;
        }
      });
      
      // 帖子长度适中加分（太短或太长都不适合作为预览）
      const contentLength = post.content.length;
      if (contentLength > 30 && contentLength < 300) {
        score += 3;
      }
      
      // 主题帖（第一个帖子）加分
      if (post === posts[0]) {
        score += 5;
      }
      
      return { post, score };
    });
    
    // 按得分排序，选取前3个高分帖子
    const topPosts = scoredPosts
      .sort((a, b) => b.score - a.score)
      .slice(0, 3)
      .map(item => item.post);
    
    // 组合预览内容
    return topPosts.map(post => `【${post.username}】: ${this.truncateText(post.content, 150)}`).join('\n\n');
  }

  /**
   * 计算主题与查询的相关性得分
   */
  private calculateRelevance(
    query: string,
    title: string,
    posts: {username: string; content: string}[]
  ): number {
    let relevance = 0;
    const lowerQuery = query.toLowerCase();
    const lowerTitle = title.toLowerCase();
    
    // 标题相关性得分（标题匹配最重要）
    if (lowerTitle.includes(lowerQuery)) {
      relevance += 10;
    }
    
    // 分词匹配
    const keywords = lowerQuery
      .replace(/[,.?!，。？！]/g, ' ')
      .split(' ')
      .filter(word => word.length > 1);
    
    keywords.forEach(keyword => {
      if (lowerTitle.includes(keyword)) {
        relevance += 5;
      }
    });
    
    // 内容相关性（关键词出现频率）
    let contentMatchCount = 0;
    posts.forEach(post => {
      const lowerContent = post.content.toLowerCase();
      keywords.forEach(keyword => {
        const regex = new RegExp(keyword, 'g');
        const matches = lowerContent.match(regex);
        if (matches) {
          contentMatchCount += matches.length;
        }
      });
    });
    
    // 内容匹配得分（最高20分）
    relevance += Math.min(contentMatchCount, 20);
    
    // 回复数量得分（最高10分）
    relevance += Math.min(posts.length, 10);
    
    return relevance;
  }

  /**
   * 智能截断文本，保持完整句子
   */
  private truncateText(text: string, maxLength: number): string {
    if (text.length <= maxLength) {
      return text;
    }
    
    // 尝试在句号处截断
    const sentenceEnd = text.lastIndexOf('。', maxLength);
    if (sentenceEnd > maxLength * 0.7) {
      return text.substring(0, sentenceEnd + 1) + "...";
    }
    
    // 尝试在逗号处截断
    const commaEnd = text.lastIndexOf('，', maxLength);
    if (commaEnd > maxLength * 0.7) {
      return text.substring(0, commaEnd + 1) + "...";
    }
    
    // 直接截断
    return text.substring(0, maxLength) + "...";
  }
} 